Write an SQL Query to swap two integer numbers without using the third variable in SQL Server.
Swap two integer numbers without using third variable in SQL Server.
296
26-Dec-2024
Updated on 02-Jan-2025
Khushi Singh
02-Jan-2025There are simple techniques to swap two integer numbers in SQL Server in which, third variable is not required including Addition and subtraction or in another way that is XOR. Here's how you can do it in SQL:
Using Addition and Subtraction:
Explanation:
@a.@bfrom the new@aand assign the result to@b. Now,@bholds the original value of@a.@b(which holds the old value of@a) from the new@a. Now,@aholds the original value of@b.Using XOR (Bitwise Operator):
Explanation:
Output:
After either method:
@a becomes 20.
@b becomes 10.
In both methods, the two variables are exchanged directly without the need to use a third variable.